<template>
  <div class="relative" style="height: 38px">
    <BorderArrowSvg position="leftBottom" />
    <BorderArrowSvg position="rightTop" />
    <Border />
  </div>
  <div>
    <div class="p-4" style="padding-bottom: 66px">
      <div class="text-2xl font-semibold mb-4">收据生成</div>
      <DynamicForm :force-column="true" :model="receiptModel" :model-form-setting="formSettingData"> </DynamicForm>
      <div class="fixed inset-x-4 flex items-center justify-center bottom-0" style="height: 66px">
        <a-button type="primary" :block="true" @click="handleCreate">预览收据</a-button>
      </div>
    </div>
    <div v-show="showReceipt">
      <div ref="receiptEl" style="width: 700px" class="bg-gray-100 text-receipt px-7">
        <div class="w-60 mx-auto px-7 border-0 border-solid border-b-2 border-receipt font-semibold">
          <div class="flex flex-row text-4xl"> <div>收</div><div class="flex-1"></div><div>据</div> </div>
          <div class="flex flex-row text-xl text-center">
            <div v-for="(el, i) in words" :key="i" class="flex-1">{{ el }}</div>
          </div>
        </div>
        <div class="border-2 border-solid border-receipt mt-5 p-4.5 whitespace-nowrap" style="font-size: 0">
          <div class="flex flex-row items-center">
            <div class="text-xl">今收到</div>
            <div class="text-blue-600 flex-1 border-0 border-b border-solid border-receipt">
              <span class="text-xl">{{ receiptModel.tenant }}</span>
              <span class="text-xl">{{ getMonthStr(receiptModel.rentMonth, receiptModel.rentMonthStr) }}的租金</span>
              <strong class="text-xl">{{ receiptModel.rent }}元 </strong>
            </div>
          </div>
          <div class="flex flex-row items-center text-blue-600 mt-4">
            <!-- <div
              class="mr-2"
              :class="{
                invisible:
                  receiptModel.elecMeterReading === receiptModel.lastElecMeterReading &&
                  receiptModel.waterMeterReading === receiptModel.lastWaterMeterReading,
              }"
            >
              {{ getMonthStr(receiptModel.readingMonth) }}月份
            </div> -->
            <div class="flex-1">
              <div class="border-0 border-b border-solid border-receipt">
                <div
                  :class="{
                    invisible:
                      receiptModel.elecMeterReading === receiptModel.lastElecMeterReading &&
                      +receiptModel.lastElecMeterReading === -1,
                  }"
                >
                  <span class="text-xl">{{ getMonthStr(receiptModel.elecMonth, receiptModel.elecMonthStr) }}</span>
                  <span class="text-xl">
                    电费：{{ receiptModel.elecMeterReading }} - {{ receiptModel.lastElecMeterReading }} =
                  </span>
                  <span class="text-xl">
                    {{ Math.abs(Number(receiptModel.elecMeterReading - receiptModel.lastElecMeterReading)) }}
                  </span>
                  <span class="text-xl">度 * {{ receiptModel.perElec }}元 =</span>
                  <strong class="text-xl">
                    {{
                      Number(
                        Math.abs(receiptModel.elecMeterReading - receiptModel.lastElecMeterReading) *
                          Number(receiptModel.perElec)
                      ).toFixed(2)
                    }}元
                  </strong>
                </div>
              </div>
              <div class="border-0 border-b border-solid border-receipt">
                <div
                  :class="{
                    invisible:
                      receiptModel.waterMeterReading === receiptModel.lastWaterMeterReading &&
                      +receiptModel.lastWaterMeterReading === -1,
                  }"
                >
                  <span class="text-xl">{{ getMonthStr(receiptModel.waterMonth, receiptModel.waterMonthStr) }}</span>
                  <span class="text-xl">
                    水费：{{ receiptModel.waterMeterReading }} - {{ receiptModel.lastWaterMeterReading }} =
                  </span>
                  <span class="text-xl">
                    {{ Math.abs(receiptModel.waterMeterReading - receiptModel.lastWaterMeterReading) }}
                  </span>
                  <span class="text-xl">度 * {{ receiptModel.perWater }}元 =</span>
                  <strong class="text-xl">
                    {{
                      Number(
                        Math.abs(receiptModel.waterMeterReading - receiptModel.lastWaterMeterReading) *
                          Number(receiptModel.perWater)
                      ).toFixed(2)
                    }}元
                  </strong>
                </div>
              </div>
            </div>
          </div>
          <div class="flex flex-row items-center mt-4">
            <div class="text-xl">金额（大写）</div>
            <div class="flex-1 border-0 border-b border-solid border-receipt text-right text-blue-600 text-xl">
              {{
                numToBig(
                  Number(receiptModel.rent) +
                    Math.abs(receiptModel.elecMeterReading - receiptModel.lastElecMeterReading) *
                      Number(receiptModel.perElec) +
                    Math.abs(receiptModel.waterMeterReading - receiptModel.lastWaterMeterReading) *
                      Number(receiptModel.perWater)
                )
              }}
            </div>
          </div>
          <div class="flex flex-row items-center mt-4">
            <div class="flex-1 text-right text-xl"> ¥： </div>
            <div class="px-3 border-0 border-b border-solid border-receipt text-blue-600">
              <strong class="text-xl">
                {{
                  Number(
                    Number(receiptModel.rent) +
                      Math.abs(receiptModel.elecMeterReading - receiptModel.lastElecMeterReading) *
                        Number(receiptModel.perElec) +
                      Math.abs(receiptModel.waterMeterReading - receiptModel.lastWaterMeterReading) *
                        Number(receiptModel.perWater)
                  ).toFixed(2)
                }}元
              </strong>
            </div>
          </div>
        </div>
        <div class="mt-4 text-right text-2xl">
          经手人：<span class="text-blue-600">{{ receiptModel.operator }}</span>
        </div>
      </div>
    </div>
    <div style="display: none">
      <a-image
        :width="imgWidth"
        :height="imgHeight"
        :preview="{
          visible: imgVisible,
          onVisibleChange: setImgVisible,
        }"
        :src="hideImgSrc"
      />
    </div>
  </div>
</template>
<script setup lang="ts">
import { nextTick, ref, shallowRef } from "vue";
import dayjs from "dayjs";
import { FormItemComponentType, FormItemData } from "../components/CURDDialog/models";
import { numToBig } from "/@/utils/common";
import html2canvas from "html2canvas";
import WaterMark from "l-watermark";
import type PageWaterMark from "l-watermark/dist/types/page";

interface Receipt {
  operator: string;
  tenant: string;
  date: dayjs.Dayjs;
  rent: number;
  rentMonth: dayjs.Dayjs;
  rentMonthStr: string;
  lastElecMeterReading: number;
  elecMeterReading: number;
  lastWaterMeterReading: number;
  waterMeterReading: number;
  // readingMonth: dayjs.Dayjs;
  elecMonth: dayjs.Dayjs;
  elecMonthStr: string;
  waterMonth: dayjs.Dayjs;
  waterMonthStr: "";
  perElec: number;
  perWater: number;
}

const now = dayjs();
const receiptModel = ref<Receipt>({
  operator: "林一柱",
  tenant: "",
  date: now,
  rentMonth: now,
  rentMonthStr: "",
  rent: 0,
  // readingMonth: now.add(-1, "month"),
  elecMonth: now.add(-1, "month"),
  elecMonthStr: "",
  lastElecMeterReading: 0,
  elecMeterReading: 0,
  perElec: 1.3,
  waterMonth: now.add(-1, "month"),
  waterMonthStr: "",
  lastWaterMeterReading: 0,
  waterMeterReading: 0,
  perWater: 8,
});
const formSettingData = ref<FormItemData<Partial<Receipt>>[]>([
  {
    key: "_subTitle",
    subTitle: "每月租金",
    beforeKey: "rentMonth",
  },
  {
    key: "_subTitle",
    subTitle: "电费",
    beforeKey: "elecMonth",
  },
  {
    key: "_subTitle",
    subTitle: "水费",
    beforeKey: "waterMonth",
  },
  {
    key: "_subTitle",
    subTitle: "基本信息",
    beforeKey: "operator",
  },
  {
    key: "operator",
    label: "经办人",
    required: true,
  },
  {
    key: "tenant",
    label: "租客",
    required: true,
  },
  {
    key: "date",
    type: FormItemComponentType.DATEPICKER,
    label: "收据日期",
    required: true,
    props: {
      valueFormat: "",
    },
  },
  {
    key: "rentMonth",
    type: FormItemComponentType.DATEPICKER,
    label: "租金月份",
    required: true,
    props: {
      picker: "month",
      valueFormat: "",
    },
  },
  {
    key: "rentMonthStr",
    label: "租金月份（手写）",
  },
  {
    key: "rent",
    label: "租金金额",
    required: true,
    props: {
      type: "number",
      addonAfter: "¥",
      allowClear: true,
    },
  },
  {
    key: "elecMonth",
    type: FormItemComponentType.DATEPICKER,
    label: "电表读数月份",
    required: true,
    props: {
      picker: "month",
      valueFormat: "",
    },
  },
  {
    key: "elecMonthStr",
    label: "电表读数月份（手写）",
  },
  {
    key: "lastElecMeterReading",
    label: "上月电表读数",
    required: true,
    props: {
      type: "number",
      addonAfter: "度",
      allowClear: true,
    },
  },
  {
    key: "elecMeterReading",
    label: "本月电表读数",
    required: true,
    props: {
      type: "number",
      addonAfter: "度",
      allowClear: true,
    },
  },
  {
    key: "perElec",
    label: "电费单价",
    required: true,
    props: {
      type: "number",
      addonAfter: "元/度",
      allowClear: true,
    },
  },
  {
    key: "waterMonth",
    type: FormItemComponentType.DATEPICKER,
    label: "水表读数月份",
    required: true,
    props: {
      picker: "month",
      valueFormat: "",
    },
  },
  {
    key: "waterMonthStr",
    label: "水表读数月份（手写）",
  },
  {
    key: "lastWaterMeterReading",
    label: "上月水表读数",
    required: true,
    props: {
      type: "number",
      addonAfter: "度",
      allowClear: true,
    },
  },
  {
    key: "waterMeterReading",
    label: "本月水表读数",
    required: true,
    props: {
      type: "number",
      addonAfter: "度",
      allowClear: true,
    },
  },
  {
    key: "perWater",
    label: "水费单价",
    required: true,
    props: {
      type: "number",
      addonAfter: "元/度",
      allowClear: true,
    },
  },
]);
function getMonthStr(value: dayjs.Dayjs, str: string) {
  return str || value.format("YYYY年M月份");
}

const showReceipt = ref(false);
const receiptEl = shallowRef<HTMLDivElement>();
const hideImgSrc = ref("");
const imgVisible = ref(false);
const setImgVisible = (value): void => {
  imgVisible.value = value;
};
const loading = ref(false);
const imgWidth = ref(0);
const imgHeight = ref(100);
let waterMark: PageWaterMark | undefined = void 0;
function handleCreate() {
  showReceipt.value = true;
  loading.value = true;
  nextTick(() => {
    if (receiptEl.value) {
      if (!waterMark) {
        waterMark = WaterMark.page({
          target: receiptEl.value,
          text: "林一柱收据专用",
          cSpace: 20,
          vSpace: 10,
          color: "rgba(0, 0, 0, 0.08)",
        });
      }
      const width = receiptEl.value.offsetWidth;
      const height = receiptEl.value.offsetHeight;
      imgWidth.value = width;
      imgHeight.value = height;
      html2canvas(receiptEl.value).then(function (canvas) {
        hideImgSrc.value = canvas.toDataURL("image/jpeg", 1.0);
        setImgVisible(true);
        loading.value = false;
        showReceipt.value = false;
      });
    }
  });
}

const words = ["R", "E", "C", "E", "I", "P", "T"];
</script>
